package com.lotusfall.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.lotusfall.config.AliYunConfig;
import com.lotusfall.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class PicUploadService {

    @Autowired
    private OSS ossClient;
    @Autowired
    private AliYunConfig aliYunConfig;
    private static final String[] IMAGE_TYPE = new String[]{
            ".bmp",".jpg",".jpeg",".gif",".png"
    };


    private boolean isLegal(String filename){
        for(String type:IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(filename,type)){
                return true;
            }
        }
        return false;
    }
    public PicUploadResult upload(MultipartFile multipartFile){
        PicUploadResult picUploadResult = new PicUploadResult();

        // 后缀名校验
        if(!isLegal(multipartFile.getOriginalFilename())){
            picUploadResult.setStatus("格式错误！上传失败！");
            return picUploadResult;
        }
        String filePath = getFilePath(multipartFile.getOriginalFilename());
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliYunConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()));

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            System.out.println(result.getResponse().getStatusCode());

            picUploadResult.setStatus("done");
            picUploadResult.setName(this.aliYunConfig.getUrlPrefix() + filePath);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            picUploadResult.setStatus("上传失败！！");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return picUploadResult;
    }

    private String getFilePath(String sourceFileName){
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis()
                + RandomUtils.nextInt(100,9999) + "."
                + StringUtils.substringAfterLast(sourceFileName,".");
    }


}
